import { EventEmitter, on } from "events";
import gloabs from '../common/Globals'
import { isArray } from "lodash";
import { TABLES } from '../entity'
import { DataSource } from 'typeorm'

type RCD = Record<string, any>;

async function connect(){
    const connect = await gloabs.getGlobal('connection');
    return connect
}

async function _model( tables: Array<string> | string | undefined): Promise< Record<string, DataSource> | any > {
    const re:RCD = {}
    if( !tables){
        const fn = (): Promise< Record<string, object> >=>{
            return new Promise((resolve, reject)=>{
                resolve({Model: new this()})
            });
        }
        return await fn()
    }
    const _connect = await connect()
    const tlist = isArray(tables) ? tables : [tables]
    tlist.forEach( (v: any):any => {
        if(!v) return;
        re[v] = _connect.getRepository(TABLES[v]);
    })
    return re
}

_model.prototype = Object.assign( {

}, EventEmitter.prototype)

export default _model